package com.websocket;

import com.protos.Peer;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import static java.lang.Thread.sleep;

public class wsCbClient extends WebSocketClient {

    private List<Peer.Event> eventsList = new Vector<>(); //event列表，主要是用来确认交易是否入块

    public wsCbClient(URI serverUri, Draft draft) {
        super(serverUri, draft);
    }

    public wsCbClient(URI serverURI) {
        super(serverURI);
    }

    public wsCbClient(URI serverUri, Map<String, String> httpHeaders ) {
        super(serverUri, httpHeaders);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("opened connection");
    }

    @Override
    public void onClose(int code, String reason, boolean remote ) {
        // The codecodes are documented in class org.java_websocket.framing.CloseFrame
        System.out.println( "Connection closed");
    }

    @Override
    public void onMessage(String message) {
        System.out.println("received message: " + message);
    }

    /**
     *
     * @param message
     */
    @Override
    public void onMessage(ByteBuffer message) {
        try {
            byte[] bytes = new byte[message.capacity()];
            message.get(bytes, 0, bytes.length);
            Peer.Event event = Peer.Event.parseFrom(bytes);
            eventsList.add(event);
            System.out.println(System.currentTimeMillis());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("an error occurred:" + ex);
    }


    /**
     *
     * @param callBack
     * @param transaction
     */
    public void feedBack(wsCallBack callBack, Peer.Transaction transaction) {
//        eventsList = new ArrayList<>();
        while (this.isOpen()) {
            while (!eventsList.isEmpty()) {
                if (eventsList.get(0).hasBlk()) {
                    Peer.Block block = eventsList.get(0).getBlk();
                    for (Peer.Transaction tran : block.getTransactionsList()) {
                        if (tran.getTxid().equals(transaction.getTxid())) {
                            System.out.println(transaction.getTxid() +"&&"+ eventsList.size());
                            callBack.verifyBlock(true, block, "确认出块");
                            eventsList.clear();
                            try {
                                this.getSocket().close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                if (!eventsList.isEmpty()) {
                    eventsList.remove(0);
                }
            }
        }
//        int num = 0;
//        while (!eventsList.isEmpty()) {
//            num++;
//            if (eventsList.get(0).hasBlk()) {
//                Peer.Block block = eventsList.get(0).getBlk();
//                for (Peer.Transaction tran:block.getTransactionsList()) {
//                    if (tran.getTxid().equals(transaction.getTxid())) {
//                        callBack.verifyBlock(true, block);
//                        eventsList.clear();
////                        eventsList = null;
//                        try {
//                            this.getSocket().close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
////                        System.out.println(this.isOpen());
//                    }
//                }
//            }
//            if (!eventsList.isEmpty()) {
//                System.out.println(System.currentTimeMillis());
//                try {
//                    sleep(40);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println(System.currentTimeMillis());
//                eventsList.remove(0);
//            }
//        }
//        System.out.println(num);
    }
}

